﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Collections;
using System.Text.RegularExpressions;
using System.Security.Cryptography;

namespace DusonFramework.Core
{
    public class FileHelper : IDisposable
    {
        public void Dispose()
        {
            GC.SuppressFinalize(this);
        }

        #region 文件创建
        /// <summary>
        /// Create File to localhost
        /// </summary>
        /// <param name="Context">File Context</param>
        /// <param name="Path">Save Path(example:C:\tempfile)</param>
        /// <param name="FileExtendMame">ExtendName(example:exe、bmp)</param>
        /// <returns></returns>
        public static string CreateTempFile(byte[] Context, string Path, string FileExtendMame)
        {
            if (!Directory.Exists(Path)) Directory.CreateDirectory(Path);
            System.Threading.Thread.Sleep(10);
            string FullName = DateTime.Now.ToBinary().ToString() + "." + FileExtendMame;
            System.IO.FileStream fs = File.Create(Path + @"\" + FullName);
            fs.Write(Context, 0, Context.Length);
            fs.Flush();
            fs.Close();
            return FullName;
        }

        public static void CreateTempFile(string Path, byte[] Context, string FileName)
        {
            if (!Directory.Exists(Path))
            {
                Directory.CreateDirectory(Path);
            }
            System.Threading.Thread.Sleep(10);
            System.IO.FileStream fs = File.Create(Path + @"\" + FileName);
            fs.Write(Context, 0, Context.Length);
            fs.Flush();
            fs.Close();
        }

        /// <summary>
        /// 创建文件
        /// </summary>
        /// <param name="path">文件路径</param>
        /// <param name="content">文件内容</param>
        public static void Create(string path, byte[] content)
        {
            FileHelper.EnsurePath(Path.GetDirectoryName(path));
            FileStream stream1 = new FileStream(path, FileMode.OpenOrCreate);
            stream1.Write(content, 0, content.Length);
            stream1.Close();
        }

        /// <summary>
        /// 创建文件
        /// </summary>
        /// <param name="path">文件路径</param>
        /// <param name="content">文件内容</param>
        public static void Create(string path, string content)
        {
            FileHelper.EnsurePath(Path.GetDirectoryName(path));
            FileStream stream1 = new FileStream(path, FileMode.OpenOrCreate);
            StreamWriter writer1 = new StreamWriter(stream1);
            writer1.WriteLine(content);
            writer1.Close();
            stream1.Close();
        }

        /// <summary>
        /// 创建文件
        /// </summary>
        /// <param name="path">文件路径</param>
        /// <param name="content">文件内容</param>
        /// <param name="encoding">内容编码</param>
        public static void Create(string path, string content, Encoding encoding)
        {
            FileHelper.EnsurePath(Path.GetDirectoryName(path));
            FileStream stream1 = new FileStream(path, FileMode.OpenOrCreate);
            StreamWriter writer1 = new StreamWriter(stream1, encoding);
            writer1.WriteLine(content);
            writer1.Close();
            stream1.Close();
        }

        /// <summary>
        /// 新建或打开现有文件，并添加内容
        /// </summary>
        /// <param name="path">文件路径</param>
        /// <param name="content">文件内容</param>
        public static void CreateAppend(string path, string content)
        {
            FileHelper.EnsurePath(Path.GetFullPath(path));
            FileStream stream1 = new FileStream(path, FileMode.Append, FileAccess.Write);
            StreamWriter writer1 = new StreamWriter(stream1);
            writer1.WriteLine(content);
            writer1.Close();
            stream1.Close();
        }

        /// <summary>
        /// 新建或打开现有文件，并添加内容
        /// </summary>
        /// <param name="path">文件路径</param>
        /// <param name="content">文件内容</param>
        /// <param name="encoding">内容编码</param>
        public static void CreateAppend(string path, string content, Encoding encoding)
        {
            FileHelper.EnsurePath(Path.GetFullPath(path));
            FileStream stream1 = new FileStream(path, FileMode.Append, FileAccess.Write);
            StreamWriter writer1 = new StreamWriter(stream1, encoding);
            writer1.WriteLine(content);
            writer1.Close();
            stream1.Close();
        }
        #endregion

        #region Operate

        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="path">文件路径</param>
        public static void Delete(string path)
        {
            File.Delete(GetFullPath(path));
        }
        #endregion

        #region Get File Inf

        public static string GetFullPath(string path)
        {
            return path;
        }

        public static string GetFileExtName(string filePath)
        {
            int index = filePath.LastIndexOf(".");
            return index > 0 ? filePath.Substring(index) : string.Empty;
        }

        public static string GetNewFileName(string filePath)
        {
            return GetNewFileName(filePath, Guid.NewGuid().ToString());
        }

        public static string GetNewFileName(string filePath, string newName)
        {
            if (!string.IsNullOrEmpty(filePath))
                return newName + GetFileExtName(filePath);
            else
                return string.Empty;
        }
        #endregion

        #region check
        /// <summary>
        /// 判断路径是否存在，如果不存在则创建该路径目录结构
        /// </summary>
        /// <param name="path">路径</param>
        private static void EnsurePath(string path)
        {
            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);
        }

        /// <summary>
        /// 判断路径是否存在，如果不存在则创建该路径目录结构
        /// </summary>
        /// <param name="path">路径</param>
        private static void EnsureFilePath(string path)
        {
            int index = path.LastIndexOf("\\");
            if (index > 0)
                path = path.Substring(0, index);
            EnsurePath(path);
        }

        /// <summary>
        /// 判断文件是否存在
        /// </summary>
        /// <param name="path">文件路径</param>
        /// <returns></returns>
        public static bool Exists(string path)
        {
            return File.Exists(path);
        }

        /// <summary>
        /// 判断扩展名是否相同
        /// </summary>
        /// <param name="file1"></param>
        /// <param name="file2"></param>
        /// <returns></returns>
        public static bool CheckExtName(string file1, string file2)
        {
            return GetFileExtName(file1) == GetFileExtName(file2);
        }
        #endregion

        /// <summary>
        /// 读取指定文件的内容
        /// </summary>
        /// <param name="path">文件路径</param>
        /// <returns>按行排列文本内容</returns>
        public static string[] Read(string path)
        {
            string text1;
            ArrayList list1 = new ArrayList();
            FileStream stream1 = new FileStream(path, FileMode.Open);
            StreamReader reader1 = new StreamReader(stream1);
            while ((text1 = reader1.ReadLine()) != null)
            {
                list1.Add(text1);
            }
            reader1.Close();
            stream1.Close();
            return (string[])list1.ToArray(typeof(string));
        }

        /// <summary>
        /// 读取指定文件的全部内容
        /// </summary>
        /// <param name="Path">文件路径</param>
        /// <returns>文件内容</returns>
        public static string ReadALL(string Path)
        {
            ArrayList list1 = new ArrayList();
            FileStream stream1 = new FileStream(Path, FileMode.Open, FileAccess.Read, FileShare.Read);
            StreamReader reader1 = new StreamReader(stream1);

            string text1 = reader1.ReadToEnd();
            reader1.Close();
            stream1.Close();
            return text1;
        }

        /// <summary>
        /// 本地文件物理路径获取二进制数据
        /// 2007-12-8_15:59:01_by_Jie
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static byte[] GetFileContent(string filePath)
        {
            try
            {
                if (!File.Exists(filePath))
                    return null;
                FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
                byte[] retVal = new byte[(int)fs.Length];

                fs.Read(retVal, 0, (int)fs.Length);
                fs.Flush();

                fs.Close();
                return retVal;
            }
            catch (Exception)
            {
                return null;
            }
        }

        /// <summary>
        /// 返回指定目录的所有文件信息
        /// </summary>
        /// <param name="Path"></param>
        /// <param name="searchPattern"></param>
        /// <returns></returns>
        public static List<FileInfo> GetFileInfoSet(string Path, string searchPattern)
        {
            List<FileInfo> result = new List<FileInfo>();

            DirectoryInfo di = new DirectoryInfo(Path);
            if (searchPattern != null)
                result.AddRange(di.GetFiles(searchPattern));
            else
                result.AddRange(di.GetFiles());
            return result;
        }

        public static DirectoryInfo DataDirectory
        {
            get
            {
                var appDataPath = (string)AppDomain.CurrentDomain.GetData("DataDirectory") ??
                           AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
                return new DirectoryInfo(appDataPath);
            }
        }

        public static FileInfo GetUniqueFile(DirectoryInfo dir, FileInfo uploadedFile)
        {
            string fullname;
            string name = uploadedFile.Name;
            fullname = Path.Combine(dir.FullName, name);
            int counter = 1;

            while (System.IO.File.Exists(fullname) == true)
            {
                string basename = Path.GetFileNameWithoutExtension(name);
                string ext = Path.GetExtension(name);
                fullname = Path.Combine(dir.FullName, String.Format("{0}{1:d3}{2}",
                                                         Path.GetFileNameWithoutExtension(name),
                                                         counter,
                                                         Path.GetExtension(name)));
                counter++;
                if (counter >= 1000)
                {
                    throw new Exception("Could not generate unique filename during upload. Operation Aborted");
                }
            }
            return new FileInfo(fullname);

        }

        public static DirectoryInfo ImageDirectory
        {
            get
            {
                return FileHelper.GetDirectory("Images");
            }
        }

        public static DirectoryInfo FileDirectory
        {
            get { return FileHelper.GetDirectory("Files"); }
        }

        public static DirectoryInfo EmailDirectory
        {
            get { return FileHelper.GetDirectory("Email"); }
        }

        public static string GetImageMarkup(FileInfo info)
        {
            return String.Format("<img src='/Images/{0}'>", info.Name);
        }

        public static string GetFileMarkup(FileInfo info)
        {
            return String.Format("<a href='/Files/{0}' target='_blank'>{0}{1}</a>", info.Name, FileHelper.FormatBytes(info.Length));
        }

        public static DirectoryInfo GetDirectory(string relativePath)
        {
            string path = Path.Combine(DataDirectory.FullName, relativePath);
            return new DirectoryInfo(path);
        }

        public static Boolean IsImage(string filename)
        {
            string imagePattern = @"^.*\.(jpg|JPG|gif|GIF|phg|PNG|jpeg|JPEG|tif|TIF)$";
            return Regex.IsMatch(filename, imagePattern);
        }

        public static Boolean isImage(FileInfo info)
        {
            return IsImage(info.FullName);
        }

        public static string GetContentType(string filename)
        {
            FileInfo file = new FileInfo(filename);
            switch (file.Extension.ToUpper())
            {
                case ".PNG": return "image/png";
                case ".JPG": return "image/jpeg";
                case "JPEG": return "image/jpeg";
                case "GIF": return "image/gif";
                case "BMP": return "image/bmp";
                case "TIFF": return "image/tiff";
                default:
                    throw new NotSupportedException("The Specified File Type is Not supported");
            }
        }

        public static string FormatBytes(long bytes)
        {
            const int scale = 1024;
            string[] orders = new string[] { "GB", "MB", "KB", "Bytes" };
            long max = (long)Math.Pow(scale, orders.Length - 1);
            foreach (string order in orders)
            {
                if (bytes > max)
                    return string.Format("{0:##.##} {1}", decimal.Divide(bytes, max), order);
                max /= scale;
            }
            return "0 Bytes";
        }

        #region 取得文件后缀名
        /****************************************
          * 函数名称：GetPostfixStr
          * 功能说明：取得文件后缀名
          * 参     数：filename:文件名称
          * 调用示列：
          *            string filename = "aaa.aspx";        
          *            string s = EC.FileObj.GetPostfixStr(filename);         
         *****************************************/
        /// <summary>
        /// 取后缀名
        /// </summary>
        /// <param name="filename">文件名</param>
        /// <returns>.gif|.html格式</returns>
        public static string GetPostfixStr(string filename)
        {
            int start = filename.LastIndexOf(".");
            int length = filename.Length;
            string postfix = filename.Substring(start, length - start);
            return postfix;
        }
        #endregion

        #region 写文件
        /****************************************
          * 函数名称：WriteFile
          * 功能说明：写文件,会覆盖掉以前的内容
          * 参     数：Path:文件路径,Strings:文本内容
          * 调用示列：
          *            string Path = Server.MapPath("Default2.aspx");       
          *            string Strings = "这是我写的内容啊";
          *            EC.FileObj.WriteFile(Path,Strings);
         *****************************************/
        /// <summary>
        /// 写文件
        /// </summary>
        /// <param name="Path">文件路径</param>
        /// <param name="Strings">文件内容</param>
        public static void WriteFile(string Path, string Strings)
        {
            if (!System.IO.File.Exists(Path))
            {
                System.IO.FileStream f = System.IO.File.Create(Path);
                f.Close();
            }
            System.IO.StreamWriter f2 = new System.IO.StreamWriter(Path, false, System.Text.Encoding.GetEncoding("gb2312"));
            f2.Write(Strings);
            f2.Close();
            f2.Dispose();
        }

        /// <summary>
        /// 写文件
        /// </summary>
        /// <param name="Path">文件路径</param>
        /// <param name="Strings">文件内容</param>
        /// <param name="encode">编码格式</param>
        public static void WriteFile(string Path, string Strings, Encoding encode)
        {
            if (!System.IO.File.Exists(Path))
            {
                System.IO.FileStream f = System.IO.File.Create(Path);
                f.Close();
            }
            System.IO.StreamWriter f2 = new System.IO.StreamWriter(Path, false, encode);
            f2.Write(Strings);
            f2.Close();
            f2.Dispose();
        }
        #endregion

        #region 读文件
        /****************************************
          * 函数名称：ReadFile
          * 功能说明：读取文本内容
          * 参     数：Path:文件路径
          * 调用示列：
          *            string Path = Server.MapPath("Default2.aspx");       
          *            string s = EC.FileObj.ReadFile(Path);
         *****************************************/
        /// <summary>
        /// 读文件
        /// </summary>
        /// <param name="Path">文件路径</param>
        /// <returns></returns>
        public static string ReadFile(string Path)
        {
            string s = "";
            if (!System.IO.File.Exists(Path))
                s = "不存在相应的目录";
            else
            {
                StreamReader f2 = new StreamReader(Path, System.Text.Encoding.GetEncoding("gb2312"));
                s = f2.ReadToEnd();
                f2.Close();
                f2.Dispose();
            }

            return s;
        }

        /// <summary>
        /// 读文件
        /// </summary>
        /// <param name="Path">文件路径</param>
        /// <param name="encode">编码格式</param>
        /// <returns></returns>
        public static string ReadFile(string Path, Encoding encode)
        {
            string s = "";
            if (!System.IO.File.Exists(Path))
                s = "不存在相应的目录";
            else
            {
                StreamReader f2 = new StreamReader(Path, encode);
                s = f2.ReadToEnd();
                f2.Close();
                f2.Dispose();
            }

            return s;
        }
        #endregion

        #region 追加文件
        /****************************************
          * 函数名称：FileAdd
          * 功能说明：追加文件内容
          * 参     数：Path:文件路径,strings:内容
          * 调用示列：
          *            string Path = Server.MapPath("Default2.aspx");     
          *            string Strings = "新追加内容";
          *            EC.FileObj.FileAdd(Path, Strings);
         *****************************************/
        /// <summary>
        /// 追加文件
        /// </summary>
        /// <param name="Path">文件路径</param>
        /// <param name="strings">内容</param>
        public static void FileAdd(string Path, string strings)
        {
            StreamWriter sw = File.AppendText(Path);
            sw.Write(strings);
            sw.Flush();
            sw.Close();
        }
        #endregion

        #region 拷贝文件
        /****************************************
          * 函数名称：FileCoppy
          * 功能说明：拷贝文件
          * 参     数：OrignFile:原始文件,NewFile:新文件路径
          * 调用示列：
          *            string orignFile = Server.MapPath("Default2.aspx");     
          *            string NewFile = Server.MapPath("Default3.aspx");
          *            EC.FileObj.FileCoppy(OrignFile, NewFile);
         *****************************************/
        /// <summary>
        /// 拷贝文件
        /// </summary>
        /// <param name="OrignFile">原始文件</param>
        /// <param name="NewFile">新文件路径</param>
        public static void FileCoppy(string orignFile, string NewFile)
        {
            File.Copy(orignFile, NewFile, true);
        }

        #endregion

        #region 删除文件
        /****************************************
          * 函数名称：FileDel
          * 功能说明：删除文件
          * 参     数：Path:文件路径
          * 调用示列：
          *            string Path = Server.MapPath("Default3.aspx");    
          *            EC.FileObj.FileDel(Path);
         *****************************************/
        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="Path">路径</param>
        public static void FileDel(string Path)
        {
            File.Delete(Path);
        }
        #endregion

        #region 移动文件
        /****************************************
          * 函数名称：FileMove
          * 功能说明：移动文件
          * 参     数：OrignFile:原始路径,NewFile:新文件路径
          * 调用示列：
          *             string orignFile = Server.MapPath("../说明.txt");    
          *             string NewFile = Server.MapPath("http://www.cnblogs.com/说明.txt");
          *             EC.FileObj.FileMove(OrignFile, NewFile);
         *****************************************/
        /// <summary>
        /// 移动文件
        /// </summary>
        /// <param name="OrignFile">原始路径</param>
        /// <param name="NewFile">新路径</param>
        public static void FileMove(string orignFile, string NewFile)
        {
            File.Move(orignFile, NewFile);
        }
        #endregion

        #region 在当前目录下创建目录
        /****************************************
          * 函数名称：FolderCreate
          * 功能说明：在当前目录下创建目录
          * 参     数：OrignFolder:当前目录,NewFloder:新目录
          * 调用示列：
          *            string orignFolder = Server.MapPath("test/");    
          *            string NewFloder = "new";
          *            EC.FileObj.FolderCreate(OrignFolder, NewFloder);
         *****************************************/
        /// <summary>
        /// 在当前目录下创建目录
        /// </summary>
        /// <param name="OrignFolder">当前目录</param>
        /// <param name="NewFloder">新目录</param>
        public static void FolderCreate(string orignFolder, string NewFloder)
        {
            Directory.SetCurrentDirectory(orignFolder);
            Directory.CreateDirectory(NewFloder);
        }
        #endregion

        #region 递归删除文件夹目录及文件
        /****************************************
          * 函数名称：DeleteFolder
          * 功能说明：递归删除文件夹目录及文件
          * 参     数：dir:文件夹路径
          * 调用示列：
          *            string dir = Server.MapPath("test/");  
          *            EC.FileObj.DeleteFolder(dir);       
         *****************************************/
        /// <summary>
        /// 递归删除文件夹目录及文件
        /// </summary>
        /// <param name="dir"></param>
        /// <returns></returns>
        public static void DeleteFolder(string dir)
        {
            if (Directory.Exists(dir)) //如果存在这个文件夹删除之
            {
                foreach (string d in Directory.GetFileSystemEntries(dir))
                {
                    if (File.Exists(d))
                        File.Delete(d); //直接删除其中的文件
                    else
                        DeleteFolder(d); //递归删除子文件夹
                }
                Directory.Delete(dir); //删除已空文件夹
            }

        }
        #endregion

        #region 将指定文件夹下面的所有内容copy到目标文件夹下面 果目标文件夹为只读属性就会报错。
        /****************************************
          * 函数名称：CopyDir
          * 功能说明：将指定文件夹下面的所有内容copy到目标文件夹下面 果目标文件夹为只读属性就会报错。
          * 参     数：srcPath:原始路径,aimPath:目标文件夹
          * 调用示列：
          *            string srcPath = Server.MapPath("test/");  
          *            string aimPath = Server.MapPath("test1/");
          *            EC.FileObj.CopyDir(srcPath,aimPath);   
         *****************************************/
        /// <summary>
        /// 指定文件夹下面的所有内容copy到目标文件夹下面
        /// </summary>
        /// <param name="srcPath">原始路径</param>
        /// <param name="aimPath">目标文件夹</param>
        public static void CopyDir(string srcPath, string aimPath)
        {
            try
            {
                // 检查目标目录是否以目录分割字符结束如果不是则添加之
                if (aimPath[aimPath.Length - 1] != Path.DirectorySeparatorChar)
                    aimPath += Path.DirectorySeparatorChar;
                // 判断目标目录是否存在如果不存在则新建之
                if (!Directory.Exists(aimPath))
                    Directory.CreateDirectory(aimPath);
                // 得到源目录的文件列表，该里面是包含文件以及目录路径的一个数组
                //如果你指向copy目标文件下面的文件而不包含目录请使用下面的方法
                //string[] fileList = Directory.GetFiles(srcPath);
                string[] fileList = Directory.GetFileSystemEntries(srcPath);
                //遍历所有的文件和目录
                foreach (string file in fileList)
                {
                    //先当作目录处理如果存在这个目录就递归Copy该目录下面的文件

                    if (Directory.Exists(file))
                        CopyDir(file, aimPath + Path.GetFileName(file));
                    //否则直接Copy文件
                    else
                        File.Copy(file, aimPath + Path.GetFileName(file), true);
                }

            }
            catch (Exception ee)
            {
                throw new Exception(ee.ToString());
            }
        }
        #endregion

        #region 分割文件
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sourceFilePath"></param>
        /// <param name="data"></param>
        /// <param name="newFileName"></param>
        public static bool SplitFile(string sourceFilePath, string targetDir, string newFileName, out int partFileCount)
        {
            int PART_FILE_SIZE = 512;

            FileStream fileStream = null;
            FileStream partFileStream = null;
            MD5CryptoServiceProvider md5Provider = null;
            partFileCount = 0;
            try
            {
                fileStream = new FileStream(sourceFilePath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
                int read = 0;
                int idx = 0;
                partFileCount = Convert.ToInt32(fileStream.Length / PART_FILE_SIZE); // 计算总有多少个小文件
                if (fileStream.Length > PART_FILE_SIZE * partFileCount)
                {
                    partFileCount += 1;
                }
                byte[] buff = new byte[PART_FILE_SIZE];

                while (true)
                {
                    read = fileStream.Read(buff, 0, buff.Length);
                    if (read == 0)
                    {
                        break;
                    }
                    ++idx;
                    if (!Directory.Exists(targetDir))
                    {
                        Directory.CreateDirectory(targetDir);
                    }
                    string partFileName = string.Format("{0}\\{1}{2}.{3}-{4:D5}.part", targetDir, newFileName, Path.GetExtension(sourceFilePath), partFileCount, idx);

                    partFileStream = new FileStream(partFileName, FileMode.Create); // 保存分割的文件                                                        

                    md5Provider = new MD5CryptoServiceProvider();
                    byte[] b = md5Provider.TransformFinalBlock(buff, 0, Convert.ToInt32(read));
                    b = md5Provider.Hash;
                    md5Provider.Clear();

                    if (!AddHeader(partFileStream, b))
                    {
                        return false;
                    }

                    partFileStream.Write(buff, 0, read);

                    partFileStream.Flush();
                    partFileStream.Close();
                }
                return true;
            }
            finally
            {
                if (fileStream != null)
                {
                    fileStream.Close();
                    fileStream = null;
                }
                if (partFileStream != null)
                {
                    partFileStream.Close();
                    partFileStream = null;
                }
                if (md5Provider != null)
                {
                    md5Provider.Clear();
                }
            }
        }

        /// <summary>
        /// 写文件头信息，steam 必须是空
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="bytes"></param>
        public static bool AddHeader(Stream stream, byte[] inputBuffer)
        {
            const int PART_FILE_HEAD_SIZE = 256;

            stream.Write(BitConverter.GetBytes(PART_FILE_HEAD_SIZE), 0, 4);
            stream.Write(inputBuffer, 0, inputBuffer.Length);
            int reserved = PART_FILE_HEAD_SIZE - 4 - inputBuffer.Length;
            stream.Write(new byte[reserved], 0, reserved);
            return true;
        }

        /// <summary>
        /// 合并文件
        /// </summary>
        private bool MergerFile(string dir, string fileName)
        {
            const int PART_FILE_HEAD_SIZE = 256;

            FileStream writeStream = null;

            try
            {
                writeStream = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
                int i = 0;
                string[] subFiles = Directory.GetFiles(dir); // 搜索所有子文件
                foreach (var subFile in subFiles.OrderBy(u => u)) // 读取子文件，并将二进制写入大文件
                {
                    FileStream readStream = new FileStream(subFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

                    byte[] bts = new byte[readStream.Length];
                    readStream.Read(bts, 0, bts.Length);
                    readStream.Close();

                    //有头信息，去掉头信息后写入stream                    
                    writeStream.Write(bts, PART_FILE_HEAD_SIZE, bts.Length - PART_FILE_HEAD_SIZE);

                    ++i;
                }
                writeStream.Flush();
                writeStream.Position = 0;

                return true;
            }
            finally
            {
                if (writeStream != null)
                {
                    writeStream.Close();
                    writeStream = null;
                }
            }
        }

        #endregion

        #region 将文本转化为指定编码(自适应4种编码)
        /// <summary>
        /// 将文本转化为指定编码(自适应4种编码)
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static string ConvertEncoding(string fileName, Encoding destEncoding)
        {
            FileStream convertFileStream = null;
            Encoding sourceEncoding = Encoding.Default;
            try
            {
                convertFileStream = File.Open(fileName, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
                BinaryReader br = new BinaryReader(convertFileStream);
                byte[] bs = br.ReadBytes(3); // 读文件的前个字节
                br.Close();
                convertFileStream.Close();

                // 确定编码
                if (bs.Length > 0)
                {
                    if (bs[0] == 0xEF && bs[1] == 0xBB && bs[2] == 0xBF)
                    {
                        sourceEncoding = Encoding.UTF8;
                    }
                    else if (bs[0] == 0xFF && bs[1] == 0xFE)
                    {
                        sourceEncoding = Encoding.Unicode;
                    }
                    else if (bs[0] == 0xFE && bs[1] == 0xFF)
                    {
                        sourceEncoding = Encoding.BigEndianUnicode;
                    }
                }

                string text = File.ReadAllText(fileName, sourceEncoding);
                File.WriteAllText(fileName, text, destEncoding);
            }
            finally
            {
                if (convertFileStream != null)
                {
                    convertFileStream.Close();
                    convertFileStream = null;
                }
            }
            return sourceEncoding.EncodingName;
        }
        #endregion

    }
}
